#!/usr/bin/python3

import requests


# 获取部门ID列表
def get_department_id(token):
    get_department_url = "https://oapi.dingtalk.com/department/list?access_token="

    get_department_url = get_department_url + token
    get_department_url = get_department_url + "&fetch_child=true"
    # get_department_url = get_department_url + "&id=1"

    resp = requests.get(get_department_url)
    result_json = resp.json()
    print(result_json)
    id_list = []
    for i in result_json['department']:
        print("name:", i['name'], ",id:", i['id'])
        id_list.append(i['id'])
    return id_list


# 获取部门用户userId列表
def get_dept_member(token, dep_ids):
    get_dept_member_url = "https://oapi.dingtalk.com/user/getDeptMember?access_token="

    get_dept_member_url = get_dept_member_url + token

    user_ids = []
    for dep_id in dep_ids:
        url = get_dept_member_url + "&deptId=" + str(dep_id)
        resp = requests.get(url)
        result_json = resp.json()
        current_user_ids = result_json['userIds']
        for user_id in current_user_ids:
            if user_ids.count(user_id) == 0:
                user_ids.append(user_id)

    return user_ids


# 获取用户详情
def get_user_id_phone(token, user_ids):
    get_user_info_url = "https://oapi.dingtalk.com/user/get?access_token="

    get_user_info_url = get_user_info_url + token

    user_list = []
    for user_id in user_ids:
        url = get_user_info_url + "&userid=" + str(user_id)
        resp = requests.get(url)
        result_json = resp.json()
        phone = result_json['mobile']
        id_phone_s = {'userid': user_id, 'phone': phone, 'name': result_json['name']}
        user_list.append(id_phone_s)

    return user_list


accessToken = input("请输入钉钉accessToken:")
# accessToken = "74869c3b8c8f33eaa9322964704bc760"
departmentIds = get_department_id(accessToken)

print("部门ID列表：")
print(departmentIds)

userIds = get_dept_member(accessToken, departmentIds)
print("用户ID列表：")
print(userIds)

userInfos = get_user_id_phone(accessToken, userIds)
print("用户信息：")
print(userInfos)
